import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:screenshot/screenshot.dart';

class ScreenShotPage extends StatefulWidget {
  const ScreenShotPage({super.key});

  @override
  State<ScreenShotPage> createState() => _ScreenShotPageState();
}

class _ScreenShotPageState extends State<ScreenShotPage> {
  final GlobalKey listViewKey = GlobalKey();
  ScreenshotController screenshotController = ScreenshotController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Screen Shot Page'),
      ),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: () async {
              saveScreen();
            },
            child: const Text('Save Screen'),
          ),
        ],
      ),
    );
  }

  Future<bool> _requestPermission() async {
    var status = await Permission.storage.request();
    return status == PermissionStatus.granted;
  }

  Future<void> saveScreen() async {
    if (!await _requestPermission()) {
      return;
    }
    ByteData? byteData = await _getByteData();

    if (byteData != null) {
      final result = await ImageGallerySaver.saveImage(
          byteData.buffer.asUint8List(),
          quality: 99);
      print(result);
    }
  }

  Future<ByteData?> _getByteData() async {
    // RenderRepaintBoundary boundary =
    //     globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary;
    ui.Image image = await createImage();
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    return byteData;
  }
  final pdf = pw.Document();

  void createPdf() {
    pdf.addPage(
      pw.Page(
        pageFormat: PdfPageFormat.a4,
        build: (pw.Context context) {
          return pw.Center(
            child: pw.Text("666"),
          ); // Center
        },
      ),
    );
  }

  Future<void> savePDF() async {
    try {
      var directory = await getExternalStorageDirectory();
      final file = File('${directory!.path}/example.pdf');
      await file.writeAsBytes(await pdf.save());
      print('PDF saved to ${file.path}');
    } catch (e) {
      print(e);
    }
  }

  Future<ui.Image> createImage() async {
    const int width = 210 * 3; // 210 mm in pixels at 3x scale
    const int height = 297 * 3; // 297 mm in pixels at 3x scale

    final recorder = ui.PictureRecorder();
    final canvas = Canvas(recorder, Rect.fromPoints(Offset(0, 0), Offset(width.toDouble(), height.toDouble())));

    final paint = Paint()
      ..color = Colors.white
      ..style = PaintingStyle.fill;

    canvas.drawRect(Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()), paint);

    final textPainter = TextPainter(
      text: const TextSpan(
        text: 'Hello, Flutter!',
        style: TextStyle(color: Colors.black, fontSize: 12),
      ),
      textDirection: TextDirection.ltr,
    );

    textPainter.layout(minWidth: 0, maxWidth: width.toDouble());
    textPainter.paint(canvas, Offset(0, 0));

    final picture = recorder.endRecording();
    final img = await picture.toImage(width, height);

    return img;
  }
}
